<template>
    <el-dialog v-model="show" title="分配角色" width="30%" :before-close="handleClose">
        <el-select v-model="selectedRoleIds" multiple placeholder="Select" style="width: 240px">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
        </el-select>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="errFn">取消</el-button>
                <el-button type="primary" @click="sureFn">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { user } from '@/api/index';
import { ElMessage } from 'element-plus';
import { computed, reactive, ref, toRefs, defineEmits, watch } from 'vue';
const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    data: {
        type: Number,
        default: 0,
    },
});

const state = reactive<{
    rollList: IRoleModel[];
}>({
    rollList: [],
});

const emit = defineEmits(['hide']);

const selectedRoleIds = ref<number[]>([]);

user.getRoleListApi().then(res => {
    if (res.code === 200) {
        state.rollList = res.data;
    }
});
// block
const handleClose = () => {
    emit('hide');
    selectedRoleIds.value = [];
};

const options = computed(() => {
    return state.rollList.map(item => ({
        value: item.id,
        label: item.name,
    }));
});
// 确认按钮
const sureFn = () => {
    // 把修改后的数据，向服务器同步
    user.updateRolesApi({
        adminId: props.data,
        roleIds: selectedRoleIds.value,
    });
    ElMessage.success('修改成功');
    emit('hide');
};

const errFn = () => {
    emit('hide');
    selectedRoleIds.value = [];
};
watch(
    () => props.data,
    () => {
        if (props.data === 0) return;
        // 向服务器发请求，得到传入的id对应的用户的所有的角色
        user.getRoleListByAdminIdApi(props.data).then(res => {
            if (res.code === 200) {
                selectedRoleIds.value = res.data.map(item => item.id);
            }
        });
    }
);
</script>

<style scoped></style>
